﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CNdotnet.Ezsocio.ContactService;
using CNdotnet.Ezsocio.PluginFramework;

namespace CNdotnet.Ezsocio.ContactFromEmail
{
    [Extension]
    public class EmailContactProvider : PlugInContextBase
    {
        private List<IEmailHandler> handlers;
        public override void Initialize()
        {
            EmailContactModule.EmailServed += new EventHandler<ServedEventArgs>(OnEmailServed);
            EmailContactModule.EmailFetch += new EventHandler<FetchEventArgs>(OnEmailFetch);

            handlers = new List<IEmailHandler>() 
            {
                new Email126Handler(),
                new Email163Handler(),
                new EmailSinaHandler()
            };
        }

        public override void Dispose()
        {
            EmailContactModule.EmailServed -= new EventHandler<ServedEventArgs>(OnEmailServed);
            EmailContactModule.EmailFetch -= new EventHandler<FetchEventArgs>(OnEmailFetch);
        }

        private void OnEmailServed(object sender, ServedEventArgs e)
        {
            List<string> data = e.Data;
            foreach (var handler in handlers)
            {
                data.Add(handler.Name);
            }
            e.Data = data;
        }

        private void OnEmailFetch(object sender, FetchEventArgs e)
        {
            int index = e.Account.IndexOf("@");
            if (index == -1)
            {
                throw new ArgumentException("Account invalid");
            }

            string email = e.Account.Substring(index + 1).ToLower();
            string userName = e.Account.Substring(0, index);
            string password = e.Password;

            IEmailHandler handler = handlers.Find(h => h.CanProcess(email));
            e.Data = handler.FetchContact(userName, password);
        }
    }
}
